package com.gym.core.common;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Joiner;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-9-1 下午2:43:23
 */
public class WebUtils {
	private final static Logger logger = LoggerFactory.getLogger(WebUtils.class);

	public static String formatRequestParameters(ServletRequest request) {
		return formatRequestParameters(request, "=", ", ");
	}

	public static String formatRequestParameters(ServletRequest request, String equal, String separator) {
		StringBuilder params = new StringBuilder();
		boolean first = true;
		for (Object name : request.getParameterMap().keySet())
			for (String value : request.getParameterValues((String) name)) {
				if (first)
					first = false;
				else
					params.append(separator);

				params.append(name).append(equal).append(value);
			}

		return params.toString();
	}

    public static String formatParameters(Map<String, String[]> params) {
        StringBuilder sb = new StringBuilder();
        if (params == null || params.isEmpty()){
            return "[]";
        }

        for(Map.Entry<String,String[]>entry : params.entrySet()){
            sb.append(entry.getKey()).append("=[");
            if (entry.getValue() != null){
                    sb.append(Joiner.on(',').join(entry.getValue()));
            }
            sb.append("] ");
        }
        return sb.toString();
    }
    
    
    
    /**
	 * 解压gzip请求
	 * @param request
	 * @return
	 */
	public static String getBodyByGzip(HttpServletRequest request) {
		
		try {
			String lenHeader = StringUtils.defaultString(request.getHeader("Content-Length"), "1024");
			GZIPInputStream gzip = new GZIPInputStream(request.getInputStream());
			
			byte[] buf = new byte[Integer.parseInt(lenHeader)];
			int len;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((len = gzip.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
			byte[] b = baos.toByteArray();
			baos.flush();
			baos.close();
			gzip.close();
			return new String(b);
		} catch (Exception e) {
			logger.error("test", e);
		}
		return "";
	}
	
	/**
	 * 转换成字符串，消耗内存，速度快
	 */
	public static String getBody(HttpServletRequest request) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null) {
			buffer.append(line);
		}
		return buffer.toString();
	}
	
	
	/**
	 * 流转化成字符串,节约内存，速度慢
	 */
	public static String getBody_(HttpServletRequest request) throws IOException {
		InputStream in = request.getInputStream();
		String content = "";
		try {
			ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
			byte[] str_b = new byte[1024];
			int i = -1;
			while ((i = in.read(str_b)) > 0) {
				outputstream.write(str_b, 0, i);
			}
			content = outputstream.toString();
		} catch (Exception e) {
			logger.error("error", e);
		}
		return content;
	}

}
